package com.itheima.common.utils;

import com.itheima.common.annotion.ExcelAttribute;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author qiankaofei
 * @version 1.0
 * @date 2020/11/19 21:31
 */
@Getter
@Setter
@SuppressWarnings(value = "all")
public class ExcelExportUtils<T> {

    /**
     * 行的索引
     */
    private Integer rowIndex;

    /**
     * 样式行的索引
     */
    private Integer styleIndex;

    /**
     * 对应实体类的属性
     */
    private Field fields[];

    private Class clazz;


    public ExcelExportUtils(Class clazz, Integer rowIndex, Integer styleIndex){
        this.clazz=clazz;
        this.rowIndex=rowIndex;
        this.styleIndex=styleIndex;
        this.fields=clazz.getDeclaredFields();
    }


    /**
     * POI基于注解导出 (Excel模板基于注解导出,以流的形式下载)
     */
    public void export(HttpServletRequest request, HttpServletResponse response, String fileName, List<T> objs, InputStream ins) throws Exception{
            //1. 在内存中创建workBook
            Workbook workbook=new XSSFWorkbook(ins);
            //2. 获取第一个工作表sheet
            Sheet sheet = workbook.getSheetAt(0);
            //3. 抽取公共样式
            Row row = sheet.getRow(styleIndex);
            CellStyle[] styles=new CellStyle[row.getLastCellNum()];
            for(Integer i=0;i<row.getLastCellNum();i++){
                styles[i]=row.getCell(i).getCellStyle();
            }
            AtomicInteger datasAi=new AtomicInteger(rowIndex);
            //填充正式数据
            for (T t : objs) {
                row = sheet.createRow(datasAi.getAndIncrement());
                for(int i=0;i<styles.length;i++) {
                    Cell cell = row.createCell(i);
                    cell.setCellStyle(styles[i]);
                    for (Field field : fields) {
                        if(field.isAnnotationPresent(ExcelAttribute.class)){
                            field.setAccessible(true);
                            ExcelAttribute ea = field.getAnnotation(ExcelAttribute.class);
                            if(i == ea.sort()) {
                                //判断字段是否为空,将其属性值设置为空字符串
                                if(field.get(t)==null){
                                    field.set(t,"".toString());
                                }
                                cell.setCellValue(field.get(t).toString());
                            }
                        }
                    }
                }
            }
            //以流的形式下载
            fileName= URLEncoder.encode(fileName,"utf-8");
            //将Excel文件以流的形式下载
            response.setContentType("application/vnd.ms-excel-templates");
            response.setCharacterEncoding("utf-8");
            //Content-disposition属性设置成以附件方式进行下载
            response.setHeader("Content-disposition", "attachment;filename="+ fileName);
            OutputStream os = response.getOutputStream();
            workbook.write(os);
            os.flush();
            os.close();
            workbook.close();
            ins.close();
        }

}
